import { Component, OnInit } from "@angular/core";
import { NzNotificationService, UploadFile } from "ng-zorro-antd";
import { Router } from "@angular/router";
import { HttpServcie } from "../../../service/http.service";
import { Config } from "../../../service/config";
import { UserBean } from "./bean/user.bean";
import { el } from "@angular/platform-browser/testing/src/browser_util";
import { NzModalService, NzModalSubject } from "ng-zorro-antd";

@Component({
  selector: "user-page",
  templateUrl: "user.html",
  styleUrls: ["user.scss"]
})
export class UserPage implements OnInit {
  constructor(
    private httpServcie: HttpServcie,
    private router: Router,
    private _notification: NzNotificationService,
    private nsub: NzModalSubject,
    private modalService: NzModalService
  ) { }
  config: any = Config;
  //接收参数
  userState = Config.USER_STATE;
  userBean: UserBean = new UserBean();
  //返回的集合
  list: any = [];
  //总页数
  total: string;
  //多选框
  allChecked: any = false;
  //多选框
  indeterminate: any = false;
  partySeleList = [];
  toParty: any;
  //设置add的
  isAddVisible = false;
  isAddConfirmLoading = false;
  inValue: string;
  currentModal: NzModalSubject;
  isConfirmLoading = false;
  modelTitle = "新增";
  updateData: any = {};
  modal: any = 0;
  totalList: any = [];
  searchOptions: any = [];
  roleTypeList: any = []; //角色类型(岗位种类)
  sureDel = false;
  picList: Array<string>;
  upLoadParam: Object = {};
  showWN: any = false;
  roleId : string;
  userName : string;

  //判断是否是admin用户
  public isTrue = false;

  ngOnInit() {
    this.userBean.pageSize = 10;
    this.userBean.currentPage = 1;
    let partyId = JSON.parse(window.localStorage["user"]).partyId;
    this.upLoadParam["partyId"] = partyId;
    this.upLoadParam["partyType"] = JSON.parse(window.localStorage["user"]).partyType;
    this.userBean.partyId = partyId;
    let type = JSON.parse(window.localStorage["user"]).type;
    this.showWN = JSON.parse(window.localStorage["user"]).partyType == "4";
    this.roleId = JSON.parse(window.localStorage["user"]).roleId;
    this.userName = JSON.parse(window.localStorage["user"]).userName;
    // 判断是否是admin用户
    if(this.roleId =="1" || this.roleId =="14" || this.roleId =="13"){
      this.isTrue = true;
    }

    //查询当前单位的用户
    if (type == "party" || this.roleId == "16"
      || this.roleId == "17" || this.roleId == "18"
      || this.roleId == "19") {
      this.userBean.type = "user";
    }else if (type != "party" && type != "user") { //超级管理员查询单位的用户
      this.userBean.type = "party";
    }else { //个人查询用户
      this.userBean.type = "user";
      this.userBean.userName = this.userName;
    }
    this.query();
  }

  //查询
  query() {
    this.httpServcie.getUserList(this.userBean).subscribe(
      data => {
        if (data.status === 200) {
          this.list = data.data.list;
          this.total = data.data.total;
        } else if (data.status === 401) {
          this.router.navigateByUrl("/login");
          return;
        } else {
          // 异常
          this._notification.create("error", "错误提示", data.message);
        }
      },
      error => {
        console.log(JSON.stringify(error));
      }
    );
  }

  // 查询面板
  panels = {
    active: true,
    name: "查询",
    disabled: false,
    childPanel: [
      {
        active: false,
        name: "查询"
      }
    ]
  };

  //table加载数据时
  displayDataChange($event) {
    this.list = $event;
    this.refreshStatus();
  }

  //重置选择框
  refreshStatus() {
    const allChecked = this.list.every(
      value => value.disabled || value.checked
    );
    const allUnChecked = this.list.every(
      value => value.disabled || !value.checked
    );
    this.allChecked = allChecked;
    this.indeterminate = !allChecked && !allUnChecked;
  }

  //全选
  checkAll(value) {
    if (value) {
      this.list.forEach(data => {
        if (!data.disabled) {
          data.checked = true;
        }
      });
    } else {
      this.list.forEach(data => (data.checked = false));
    }
  }

  //分页
  nzPageSizeChange(event) {
    this.userBean.pageSize = event;
    this.userBean.currentPage = 1;
    this.query();
  }

  //输入框的方法
  nzPageIndexChange(event) {
    this.userBean.currentPage = event;
    this.query();
  }

  //当前页
  nzPageIndexClickChange(event) {
    this.userBean.currentPage = event;
    this.query();
  }

  //添加
  //this.isAddVisible = true;
  add(titleTpl, contentTpl, footerTpl) {
    this.modelTitle = "添加";
    this.modal = 0;

    this.currentModal = this.modalService.open({
      title: titleTpl,
      content: contentTpl,
      footer: footerTpl,
      maskClosable: false,
      width: 900,
      style: {
        top: "20px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }

  //修改
  update(titleTpl, contentTpl, footerTpl) {
    this.modelTitle = "修改";
    this.modal = 1;
    const updateList: any = [];

    this.list.forEach(element => {
      if (element.checked) {
        updateList.push(element);
        this.updateData = element;
      }
    });
    if (updateList.length > 1) {
      // 异常
      this._notification.create("warning", "警告提示", "只能选中一条数据！");
      return;
    }
    if (updateList.length == 0) {
      // 异常
      this._notification.create("warning", "警告提示", "请选中一条数据！");
      return;
    }

    this.currentModal = this.modalService.open({
      title: titleTpl,
      content: contentTpl,
      footer: footerTpl,
      maskClosable: false,
      width: 900,
      style: {
        top: "20px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }

  //添加添加页面的数据
  handleOk(e) {
    this.isConfirmLoading = true;
    setTimeout(() => {
      /* destroy方法可以传入onOk或者onCancel。默认是onCancel */
      this.currentModal.destroy();
      this.isConfirmLoading = false;
      this.currentModal = null;
    }, 1000);
    // this.isAddConfirmLoading = true;
    // this.inValue = "aaaaa";
  }

  //关闭model框
  handleCancel = e => {
    console.log(e);
    this.isAddVisible = false;
  };

  //添加后返回的结果
  addOutPut(event) {
    this.isConfirmLoading = true;
    setTimeout(() => {
      /* destroy方法可以传入onOk或者onCancel。默认是onCancel */
      this.currentModal.destroy();
      this.isConfirmLoading = false;
      this.currentModal = null;
    }, 500);
    this.userBean.currentPage = 1;
    this.query();
  }

  delete() {
    const deleteList: any = [];
    const thiss: any = this;
    this.list.forEach(element => {
      if (element.checked) {
        deleteList.push(element.id + "");
      }
    });

    if (deleteList.length == 0) {
      // 异常
      this._notification.create("warning", "警告提示", "请选中一条数据！");
      return;
    }

    this.modalService.confirm({
      title: "您是否确认要删除这项内容",
      content: "<b>一旦删除，无法还原</b>",
      onOk() {
        let partyType = JSON.parse(window.localStorage["user"]).partyType;
        let partyId = JSON.parse(window.localStorage["user"]).partyId;
        let ob = thiss.httpServcie.deleteUser({ ids: deleteList,partyType:partyType,partyId:partyId}); //批量删除
        ob.subscribe(
          data => {
            if (data.status == 200) {
              thiss._notification.create("success", "成功", "删除成功！");
              thiss.userBean.currentPage = 1;
              thiss.query();
            } else {
              thiss._notification.create("error", "错误提示", data.message);
            }
          },
          error => {
            thiss._notification.create("error", "错误提示", "删除失败！");
          }
        );
      },
      onCancel() { }
    });
  }

  updateUserState() {
    const updateList: any = [];
    this.list.forEach(element => {
      if (element.checked) {
        updateList.push(element);
      }
    });
    if (updateList.length > 1) {
      // 异常
      this._notification.create("warning", "警告提示", "只能选中一条数据！");
      return;
    }
    if (updateList.length == 0) {
      // 异常
      this._notification.create("warning", "警告提示", "请选中一条数据！");
      return;
    }
    let userState = "1";
    if (updateList[0].userState == "1") {
      userState = "0";
    }
    let param = {
      id: updateList[0].id,
      userState: userState
    };

    this.httpServcie.updateUserState(param).subscribe(data => {
      if (data.status == 200) {
        this._notification.create("success", "提示", "更改成功！");
        this.query();
      } else if (data.status === 401) {
        this._notification.create("success", "提示", "登录超时，请重新登录");
        this.router.navigateByUrl("/login");
        return;
      } else {
        // 异常
        this._notification.create("error", "错误提示", data.message);
      }
    });
  }

  addMeatasisDialog(titleTpl, contentTpl, footerTpl) {
    const updateList: any = [];
    this.list.forEach(element => {
      if (element.checked) {
        updateList.push(element);
      }
    });
    if (updateList.length > 1) {
      // 异常
      this._notification.create("warning", "警告提示", "只能选中一条数据！");
      return;
    }
    if (updateList.length == 0) {
      // 异常
      this._notification.create("warning", "警告提示", "请选中一条数据！");
      return;
    }

    if (updateList[0].roleId != 5 && updateList[0].roleId != 7) {
      this._notification.create("warning", "警告提示", "该类型人员不能转移！");
      return;
    }

    let thiss = this;
    this.modalService.confirm({
      title: "您是否确认要转移这个用户",
      content: "<b>一旦转移，无法还原</b>",
      onOk() {
        thiss.querySameParty();
        thiss.currentModal = thiss.modalService.open({
          title: titleTpl,
          content: contentTpl,
          footer: footerTpl,
          maskClosable: false,
          width: 900,
          style: {
            top: "20px"
          },
          onOk() {
            console.log("Click ok");
          }
        });
      },
      onCancel() { }
    });
  }

  addMeatasis() {
    const updateList: any = [];
    this.list.forEach(element => {
      if (element.checked) {
        updateList.push(element);
      }
    });

    let type = "";
    if (updateList[0].roleId == 5) {
      type = "3";
    }
    if (updateList[0].roleId == 7) {
      type = "4";
    }

    let newPartyId = this.userBean.partyId;
    if (this.toParty) {
      newPartyId = this.toParty;
    }

    let toName = "";
    for (let party of this.partySeleList) {
      if (newPartyId == party.id) {
        toName = party.partyName;
        break;
      }
    }
    let param = {
      userId: updateList[0].id,
      userName: updateList[0].userName,
      fromId: updateList[0].partyId,
      fromName: updateList[0].partyName,
      toId: newPartyId,
      toName: toName,
      state: "1"
    };
    this.httpServcie.addMeatasis(param).subscribe(data => {
      if (data.status == 200) {
        this._notification.create("success", "提示", "提交转移申请成功！");
        this.currentModal.destroy();
        this.query();
      } else if (data.status === 401) {
        this._notification.create("success", "提示", "登录超时，请重新登录");
        this.router.navigateByUrl("/login");
        return;
      } else {
        // 异常
        this._notification.create("error", "错误提示", data.message);
      }
    });
  }

  showImage(titlepic, contentpic, footerpic, param) {
    if (param == null || param == "") {
      this._notification.create("warning", "警告提示", "资质资料不存在！");
      return;
    }
    this.picList = param.split(",");
    this.currentModal = this.modalService.open({
      title: titlepic,
      content: contentpic,
      footer: footerpic,
      maskClosable: false,
      width: 800,
      style: {
        top: "20px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }

  //上传

  showUpload(titleUpload, contentUpload, footerUpload) {
    this.currentModal = this.modalService.open({
      title: titleUpload,
      content: contentUpload,
      footer: footerUpload,
      maskClosable: false,
      width: 800,
      style: {
        top: "20px"
      },

      onOk() {
        console.log("Click ok");
      }
    });
  }

  //上传回调
  uploadChage(info: { file: UploadFile }) {
    if (info.file.status === "uploading") {
      return;
    }
    if (info.file.status === "done") {
      //设置为接口的查询不然反显有时候没用
      if (info.file.response.status != "200") {
        this._notification.create(
          "error",
          "错误提示",
          info.file.response.message
        );
      } else {
        this._notification.create("success", "提示", "导入成功");
      }
    }
  }

  querySameParty() {
    let parentId = JSON.parse(window.localStorage.getItem("user"))
      .partyParentId;
    this.httpServcie
      .queryByIdAndTypeList({
        // id: parentId,
        partyType: JSON.parse(window.localStorage.getItem("user")).partyType
      })
      .subscribe(data => {
        if (data.status == 200) {
          //物业机构
          this.partySeleList = data.data;
        }
      });
  }

  download(url, name) {
    let link = document.createElement("a");
    let body = document.querySelector("body");

    this.getBlob(this.config.IP + this.config.API.getUpload + url).then(
      blob => {
        link.href = window.URL.createObjectURL(blob);
        link.download = name;
        // fix Firefox
        link.style.display = "none";
        body.appendChild(link);
        link.click();
        body.removeChild(link);
        window.URL.revokeObjectURL(link.href);
      }
    );
  }
  getBlob(url) {
    return new Promise(resolve => {
      const xhr = new XMLHttpRequest();
      xhr.open("GET", url, true);
      xhr.responseType = "blob";
      xhr.onload = () => {
        if (xhr.status === 200) {
          resolve(xhr.response);
        }
      };
      xhr.send();
    });
  }
}
